<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Loading Topic</title>

    <link rel="icon" type="image/vnd.microsoft.icon" href="images/eckoit.ico">
    <link rel="stylesheet" type="text/css" href="styles/4col.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="styles/common.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="styles/color.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="styles/tray.css"  />
	<link rel="stylesheet" type="text/css" href="styles/smoothness/jquery-ui-1.8.6.custom.css"  />
    <link rel="stylesheet" type="text/css" href="skin/jplayer.blue.tuesday.css"  />
	<link rel="stylesheet" type="text/css" media="screen, projection" href="styles/horizontal.css" />
     <link rel="stylesheet" type="text/css" href="styles/tagit.css"  />
    <link type="text/css" rel="stylesheet" href="scripts/freebase/suggest.min.css" />
    <link type="text/css" rel="stylesheet" href="scripts/twitter/jquery.tweet.css" />

    <script type="text/javascript" src="scripts/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="scripts/jquery-ui-1.8.5.custom.min.js"></script>
    <script type="text/javascript" src="scripts/underscore-min.js"></script>
	<script type="text/javascript" src="scripts/wikid-0.2.js"></script>
	<script type="text/javascript" src="scripts/jquery.parsequery.js"></script>
	<script type="text/javascript" src="scripts/showdown.js"></script>
	<script type="text/javascript" src="scripts/jsonpath-0.8.0.js"></script>
	 <script type="text/javascript" src="scripts/jquery.corner.js"></script>
	 <script type="text/javascript" src="scripts/couch.js"></script>
	 <script type="text/javascript" src="scripts/futon.format.js"></script>
	 <script type="text/javascript" src="scripts/jquery.couch.js"></script>
	 <script type="text/javascript" src="scripts/jquery.suggest.js"></script>
	 <script type="text/javascript" src="scripts/jquery.timeago.js"></script>
	 <script type="text/javascript" src="scripts/menu.js"></script>
    <script type="text/javascript" src="scripts/jquery.md5.js"></script>
    <script type="text/javascript" src="scripts/jquery.jplayer.min.js"></script>
    <script type="text/javascript" src="scripts/shortcuts.js"></script>
    <script type="text/javascript" src="scripts/jquery.lasso.js"></script>
    <script type="text/javascript" src="scripts/jquery.heatcolor.0.0.1.js"></script>
    <script type="text/javascript" src="scripts/date.js" ></script>
    <script type="text/javascript" src="scripts/jquery.ba-bbq.min.js" ></script>
    <script type="text/javascript" src="scripts/jquery.scrollTo-1.4.2-min.js" ></script>
    <script type="text/javascript" src="scripts/wymeditor/jquery.wymeditor.min.js"></script>
    <script type="text/javascript" src="scripts/wymeditor/plugins/resizable/jquery.wymeditor.resizable.js"></script>
    <script type="text/javascript" src="scripts/jquery.loading.1.6.2.js" ></script>
    <script type="text/javascript" src="scripts/tag-it.js"></script>
    <script type="text/javascript" src="scripts/jquery-fieldselection.js"></script>
    <script type="text/javascript" src="scripts/freebase/suggest.min.js"></script>
    <script type="text/javascript" src="/_utils/script/jquery.form.js"></script>
    <script type="text/javascript" src="scripts/twitter/jquery.tweet.js"></script>
	 <script type="text/javascript">
	    $(function() {
            var wikid_id;
            var doc;
            var loadPath = false;
            var knownTypes;
            var bookmarks = [];
            var mainPlayerReady = false;
            var freebaseDataIdSelection;

            // Creating custom :external selector
            $.expr[':'].external = function(obj){
                return !obj.href.match(/^mailto\:/)
                        && (obj.hostname != location.hostname) && (obj.hostname != 'localhost')  && (obj.hostname);
            };

            $('#rightcolumn').click(function() {
                //$(this).hide('fold');
            });
            $('.selectedSpace').click(function() {
                    //$('#rightcolumn').show('fold');
            });



            $('.topicListAction,.leftListItem').live('mouseover', function() {
                if (!$(this).hasClass('topicListItemSelected') && !$(this).hasClass('topicFilter')) {
                    $(this).addClass('topicListActionHover');
                }
            }).live('mouseout',function() {
                $(this).removeClass('topicListActionHover');
            });

            $('.leftListItem').live('click', function() {
                window.location = $(this).find('a').attr('href');
            });

            $('.topicListItem').live('mouseover', function() {
                if (!$(this).hasClass('topicListItemSelected') && !$(this).hasClass('topicFilter')) {
                    $(this).addClass('topicListItemHover');
                }
            }).live('mouseout',function() {
                $(this).removeClass('topicListItemHover');
            });


            var dontScroll = false;
            $('.topicListItem').live('click', function() {
                //$('.topicListItem').removeClass('topicListItemSelected');
                $(this).removeClass('topicListItemHover')
                var topic = $(this).data('topic')
                dontScroll = true;
                if (topic) changeURL(topic);
                return false;

            });
            $('.topicListItem .ui-icon').live('click', function() {
                var parent = $(this).parent();
                var orphans = parent.data('orphans');
                $('.arrow').hide();
                if (orphans) {
                    parent.hide('slide');
                    var crumb = addFilterToBreadCrumb('Orphans');
                    crumb.find('.crumbText').show('slide', 200, function() {
                        $('.topicList').hide('slide', 150, function() {
                             $('.topicList').empty();
                            showOrphans(orphans);
                            $('.topicList').show('slide', 150);
                        });
                    });
                } else {
                    var crumb;
                    var topic = $(this).parent().data('topic');
                    if (topic) {
                        crumb = addFilterToBreadCrumb(topic);
                    } else {
                        topic = $(this).parent().data('filter');
                        crumb = addFilterToBreadCrumb(topic, 'filter');
                    }
                    parent.hide('slide');

                    crumb.find('.crumbText').show('slide', 200, function() {
                        $('.topicList').hide('slide', 150, function() {
                            $('.topicList').empty();
                            loadPath = true;
                            changeURL(wikid_id);
                            //showCurrentFilter();
                            
                        });
                    });
                }
                return false;




            });

            $('#rightcolumn').resizable({
                handles: 'e',
                minWidth: 150,
                resize: function() {
                    fixMainSize();
                }
            });

            $('.topicListFolder .ui-icon').live('mouseover', function() {
                        $(this).removeClass('ui-icon-triangle-1-e')
                               .addClass('ui-icon-circle-triangle-e');
                    }).live('mouseout',function() {
                        $(this).removeClass('ui-icon-circle-triangle-e')
                               .addClass('ui-icon-triangle-1-e');
                    });


            function addFilterToBreadCrumb(topic) {
                var crumb = $('<div class="crumb"><div class="crumbText">'+topic+'<a class="close">x</a></div></div>');
                $('.breadCrumbFilter').append(crumb);
                crumb.data('topic', topic);
                crumb.find('.close').click(function() {
                    $(this).parent().parent().remove();
                    $('.arrow').hide();
                    $('.topicList').hide('slide', 150, function() {
                         $('.topicList').empty();
                        loadPath = true;
                        changeURL(wikid_id);
                    });
                });
                return crumb;
            }

            function fixMainSize() {
                var width = $('#leftcolumn').width() + $('#rightcolumn').width();
                $('#contentwrapper').css('margin-left', '-' + width + 'px');
                $('#contentcolumn').css('margin-left',  width + 'px');
                placeArrow();
            }


            var spaces = wikid.findSpaces();
            var db_name = wikid.parseDBname(window.location);
			var db = new CouchDB(db_name);
            var settings = db.open('-settings');
            knownTypes = wikid.findKnownTypes(db, db_name);

            // any bookmarks
            $('.bookmark').remove(); //remove any existing
            if (_.isArray(settings.bookmarks)) {
                $.each(settings.bookmarks, function(i, bookmark) {
                    var img_url = wikid.topicIconUrl(bookmark.icon, db_name, knownTypes);
                    var bMark = $('<div class="leftListItem bookmark"><a href="./#'+ bookmark.path +'" ><img src="'+img_url+'" class="topicIcon"/>'+bookmark.name+'</a></div>');
                    bMark.appendTo('.selectedSpace');
                    bookmarks.push(bookmark.path);

                })
            }



            $('#bookmarkDialog').dialog({
                autoOpen: false,
                resizable: true,
                height: 240,
                width: 600,
                modal: false,
                buttons : {
                    "Save" : function() {
                        var anchor = window.location.hash.substring(1);
                        var bmark = {
                            name: $('#bookmarkName').val(),
                            path: anchor,
                            icon : {
                                type: "type",
                                icon: $('#bookmarkIcon').val()
                            }
                        }
                        settings.bookmarks = settings.bookmarks || [];
                        settings.bookmarks.push(bmark);
                        db.save(settings);

                        $(this).dialog('close');
                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });

            $.getJSON('images/icons/filename.txt', function(data) {
                $('.iconInput').autocomplete({
                    source: data,
                    max: 10,
                    focus: function(event, ui) {
                        $('.bookmarkIconImage').attr('src','images/icons/' + ui.item.label + '.png' );
                    }
                }).data("autocomplete")._renderItem = function(ul, item) {

                    return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append('<a><img src="images/icons/' + item.label + '.png" class=""/>' + item.label + '</a>')
                        .appendTo(ul);
                };
            });



            $('.bookmarkAction').click(function() {
                $('#bookmarkDialog').dialog('open');
            });


            /************************************* New Button *****/
            function saveNewTopic() {
                var newID = $('#newTopicName').val();
                var newDoc = {
                    _id : newID
                };
                var now = new Date();
                newDoc["-lastmodified"] = iso8601(now);

                newPath = [];
                $('.crumb').each(function() {
                    var topic = $(this).data('topic');
                    if (topic != 'Orphans') {
                        newPath.push(topic);
                    }

                });
                if (newPath.length > 0) {
                    newDoc['-tags'] = newPath;
                }
                db.save(newDoc);
                changeURL(newID, newPath);
            }

            $('#newTopic').dialog({
                autoOpen: false,
                resizable: true,
                height: 150,
                width: 215,
                modal: true,
                buttons : {
                    Ok: function () {
                        saveNewTopic();
                        $(this).dialog('close');


                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            }).parent().submit(function() {
                $('#newTopic').dialog('close');
                saveNewTopic();
                return false;
            });
                

            $('.newTopicAction').click(function() {
                $('#newTopic').dialog('open');
            });


            /******** From topic.html *****/
            function showTopic () {
                setupInfoSection();
                setupMarkersSection();
                console.log('open: ' + wikid_id)
                doc = db.open(wikid_id);
                if (!doc) {
                    $('#taglist').hide();
                    var readableId = wikid.titleFromTopicId(wikid_id);
                    $('.readableId').text(readableId);
                    document.title = wikid.documentTitle(readableId);
                    var add = $('<p class="notFound">This document does not exist. <a href="edit.html?' + wikid_id + '">Create it.</a></p>');
                    $('#maincontent').append(add);
                    return;
                }
                var result = wikid.toWikid(doc, db, 'wikid');
                $('.readableId').text(result.topic);
                $('#titleHolder').show();//.attr('title', wikid_id);
                document.title = result.title;

                var text_teaser = $('<div class="textTeaser" title="Edit Text"><img src="images/icons/ui-text-field.png" alt="Edit Text"  class="topicIcon"/>Edit</div>');
                function loadWiki() {
                    if (result.wiki) {
                        $('#Wiki').empty().html(result.wiki);
                    } else {
                        $('#Wiki').empty();
                    }
                    $('#Wiki').append(text_teaser);
                    $('#Wiki').removeClass('wikiHover');
                    $('.textTeaser').hide();
                }
                loadWiki();

                $('.textTeaser').live('click', function() {

                    var textArea = $('<textarea class="wymeditor"></textarea>')
                    var okButton = $('<button class="wikiTextButton">Ok</button>');
                    var cancelButton = $('<button class="wikiTextButton">Cancel</button>');
                    var editorHeight = 400;
                    //var wikiHeight = $('#Wiki').height();
                    //console.log(wikiHeight);
                    //if (wikiHeight > editorHeight) {
                    //    editorHeight = wikiHeight;
                    //}

                    $('#Wiki').empty().append(textArea)
                            .append(okButton).append(cancelButton);
                    var isDataShowing = $('#Data').is(":visible");
                    if (isDataShowing) {
                        $('#Data').hide();
                    }

                    if (result.wiki == null || result.wiki == '') {
                        result.wiki = '<p></p>'; // a default container
                    }

                    textArea.wymeditor({
                        html: result.wiki,
                        logoHtml:'',
      
                        classesHtml: '',
                        skin: 'compact',
                        toolsItems:[
                            {name: 'Bold', title: 'Bold', css:'wym_tools_strong'},
                            {name: 'Italic', title: 'Italic', css:'wym_tools_emphasis'},

                            {'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'},
                            {'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'},    
                            {'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
                            {'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
                            {'name': 'CreateLink', 'title': 'External_Link', 'css': 'wym_tools_link'},
                            {'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
                            {'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
                            {'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},

                        ],
                        postInit: function(wym) {
                           //
                            wym.resizable();



                            // fix up the 'containers' thing
                            $('.wym_containers h2').text('')
                                    .append('<img src="images/icons/edit-size-down.png" style="margin-top: 3px;"/>')
                                    .css({border: 'none', background: 'none'})
                                    .parent().css({width: '22px', border: 'none', background: 'none'})
                                    .insertBefore('.wym_tools');

                            // add the internal link button
                            var wikilink = "<li class='wym_tools_wikilink'>"
                                 + "<a href='#'"
                                 + " title='Link To Existing Topic'"
                                 + " style='background-image:"
                                 + " url(images/icons/chain.png); background-position: center center;'>"
                                 + "WikiLink"
                                 + "</a></li>";

                            //add the button to the tools box
                            jQuery(wym._box)
                            .find('.wym_tools_link')
                            .before(wikilink);

                             //handle click event on wrap button
                            jQuery(wym._box)
                            .find('li.wym_tools_wikilink a').click(function() {
                                var sel = wym._iframe.contentWindow.getSelection();
                                //console.log(sel.getRangeAt(0).toString());
                                $('#wikiLinks').data('editor',wym).dialog('open');
                                return(false);
                            });
                            okButton.click(function() {
                                doc['-wiki'] = {
                                    type: 'xhtml',
                                    text: wym.xhtml()
                                };
                                db.save(doc);
                                result.wiki = doc['-wiki'].text;
                                loadWiki();
                                if (isDataShowing) {
                                    $('#Data').show();
                                }
                            });


                            // add the new topic button
                            var newtopic = "<li class='wym_tools_newtopic'>"
                                 + "<a href='#'"
                                 + " title='Create A New Topic From Selected Text'"
                                 + " style='background-image:"
                                 + " url(images/icons/grey-document--plus.png); background-position: center center;'>"
                                 + "NewTopic"
                                 + "</a></li>";

                            //add the button to the tools box
                            jQuery(wym._box)
                            .find('.wym_tools_wikilink')
                            .before(newtopic);

                            $('.wym_tools_newtopic a').click(function() {
                                var sel = wym._iframe.contentWindow.getSelection();
                                if (!sel || !sel.getRangeAt(0)) return false;
                                var newTopicText = sel.getRangeAt(0).toString();
                                if (!newTopicText) return false;
                                newTopicText = wikid.topicIdFromTitle(newTopicText);


                                var newDoc = {
                                    _id : newTopicText,
                                    '-tags' : [wikid_id],
                                    '-lastmodified' : iso8601(new Date())
                                };
                                db.save(newDoc);
                                var url = '#' + newTopicText;
                                wym.wrap('<a href="'+url+'">','</a>');
                                return(false);
                            });



                            $('.wym_box').find('iframe').height(editorHeight);

                        }
                    });
                    cancelButton.click(function(){
                        loadWiki();
                        if (isDataShowing) {
                            $('#Data').show();
                        }
                    });
                });



                $('#Wiki').live('mouseover', function() {
                   $(this).addClass('wikiHover');
                    $('.textTeaser').show().position({
                        my:'left bottom',
                        at: 'left top',
                        of: $('#Wiki')
                    });
                }).live('mouseout', function() {
                   $(this).removeClass('wikiHover');
                    _.delay(function() {
                        if (! $('#Wiki').hasClass('wikiHover')) {
                            $('.textTeaser').hide();
                        }
                    }, 600)
                });



                var lastmodified_val = result.doc['-lastmodified'];
                if (lastmodified_val) {
                    var lastmodified = $.timeago(lastmodified_val);
                    $('#lastmodified').show().text('(updated '+ lastmodified + ')');
                }

                
                var icon = db.view('system/by_icons',{}, [wikid_id]).rows[0].value;
                if (doc['-tags'] && doc['-tags'].length > 0) {
                    icon.parent = doc['-tags'][0];
                }
                var icon_url = wikid.topicIconUrl(icon, db_name, knownTypes);
                $('.mainTopicImage').attr('src', icon_url);

                // tags that have data
                $('#Data').empty();
                jQuery.each(result.fields, function(i) {
                    var field = result.fields[i].name;
                    var row = $('<div class="tagdata corner"><div class="tagdataheader">' + field + '</div><div class="val"></div></div>');
                    row.find(".val").append(_renderValue(result.fields[i].value));
                    $('#Data').append(row);

                    // console.dir(wikid);
                    // if the field has a process function
                    if (wikid[field] && wikid[field].process) {
                        wikid[field].process(result);
                    }

                });

                // attachments
                if (result.attachments && result.attachments.length) {
                    var row = $('<div class="tagdata corner"><div class="tagdataheader">Attachments</div><ul class="val"></div></div>');
                    jQuery.each(result.attachments, function(i, attachment) {
                        row.find(".val").append('<li><a href="/' + db_name + '/' +  wikid_id + '/' + attachment.name +'">' + attachment.name + '</a></li>');
                    });
                    $('#Data').append(row);
                }

                $("#tagged_as").empty();


                if (result.tagged && result.tagged.length > 0) {
                    $("#tagged_title").text("See Also");
                    if (result.tagged && result.tagged.length > 0) {
                        $.each(result.tagged, function(i, tag) {
                            var link = $("<li><a class='topic' href='"+ tag.href +"'>"+ tag.alias + "</a></li>");
                            $("#tagged_as").append(link);
                        });
                    }
                } else {
                    $('#tagged_title').hide();
                }

                function displayTags(tags ) {
                     if (tags && tags.length > 0) {
                        $('#taglist').show().empty();
                        $.each(tags, function(i, tag) {
                            $('#taglist').append('<a class="topic" href="' + tag.href +  '">' + tag.alias + '</a><span>&nbsp;</span>');
                        });
                    } else {
                        $('#taglist').empty().show();
                    }
                    $('#taglist').append('<div class="tagTeaser" title="Edit Tags"><img src="images/icons/ui-text-field.png" alt="Edit Tags"  class="topicIcon"/>Edit</div>');
                }

                displayTags(result.tags);

                $('.tagTeaser').live('click', function() {

                     $('#taglist').empty().append('<ul id="tag_tags"></ul><button id="tag_ok">Ok</button><button id="tag_cancel">Cancel</button>');

                    var existingTags = doc['-tags'] || [];
                     $("#tag_tags").tagit({
                        existingTags : existingTags,
                        tagSource :  function(request, response) {
                            var term = request.term;
                            var matches = db.view('system/topics', {
                                startkey: term,
                                endkey: term + 'zzz',
                                limit: 30
                            });
                            response(_.map(matches.rows, function(row) { return  row.id }));
                        }
                    });
                    $('.tagit-input').focus();
                });

                $('#tag_ok').die().live('click', function() {
                    console.log('click!');
                    var localtags = [];
                    $(".tagit-choice").each(function() {
                        localtags.push($(this).children("input").val());
                    });
                    doc['-tags'] = localtags;
                    console.log(doc);
                    db.save(doc);
                    result.tags = wikid.toTagList(doc['-tags']);
                    displayTags(result.tags);
                    // update each of the timestamps of the tags
                    _.delay(function(localtags2) {
                        $.each(localtags2, function(i, tag) {
                            var localdoc = db.open(tag);
                            if (!localdoc) {
                                localdoc = {};
                                localdoc._id = tag;
                            };
                            var now = new Date();
                            localdoc["-lastmodified"] = iso8601(now);
                            db.save(localdoc);
                        });
                    },100, localtags );
                });
                $('#tag_cancel').die().live('click', function() {
                    displayTags(result.tags);
                });


                $('#taglist').droppable({
                        hoverClass: "ui-state-active",
                        drop: function( event, ui ) {
                            var topicToAdd = ui.draggable[0].title;
                            var tag = wikid.getTagLink(topicToAdd);
                            $('#taglist').append('<a class="topic" href="' + tag.href +  '">' + tag.alias + '</a><span>&nbsp;</span>');
                            if (!_.isArray(doc['-tags'])) {
                                doc['-tags'] = [];
                            }
                            doc['-tags'].push(topicToAdd);
                            db.save(doc);

                        }
                    }).live('mouseover', function() {
                       $(this).addClass('wikiHover');
                        $('.tagTeaser').show().position({
                            my:'left bottom',
                            at: 'left top',
                            of: this
                        });
                    }).live('mouseout', function() {
                       $(this).removeClass('wikiHover');

                        _.delay(function() {
                            if (! $('#taglist').hasClass('wikiHover')) {
                                $('.tagTeaser').hide();
                            }
                        }, 600)
                    });

                // freebase
                if (result.freebaseLink ) {
                    var row = $('<div class="tagdata corner freebase"><div class="val"></div> <div class="freebase-attribution"> <img alt="Freebase CC-BY" height="23px" style="float: left; border: 0;" width="61px" src="http://www.freebase.com/policies/freebase-cc-by-61x23.png"/> <div style="font-size: x-small; margin-left: 70px; height: 30px; "> Source: <a href="http://www.freebase.com/view' +result.doc['-freebase_id']+ '"><span class="fbs-att-title">Topic</span></a> on <a href="http://www.freebase.com/">Freebase</a>, licensed under <a href="http://creativecommons.org/licenses/by/2.5/">CC-BY</a></div> </div> </div>');
                    $.get(result.freebaseLink, null, function(data, status){
                        row.find(".val").html(data.html);
                        $('.fbs-att-title').text($('#fbs-flyout-title').text());
                    }, 'jsonp');
                    $('#Data').append(row);
                }


                // facebook
                if (result.facebookDetails) {
                   var row2 = $('<div class="tagdata corner"><div class="tagdataheader">Facebook</div> <div class="val"></div></div>');
                    $.get(result.facebookDetails.graphUrl, null, function(data, status){
                        var toShow = { name: data.name};
                        if (data.gender) toShow.gender = data.gender;
                        row.find(".val").append(_renderValue(data));
                        if (data.link) {
                            row.click(function() {
                                window.location = data.link;
                            });
                        }
                    }, 'jsonp');
                    $('#Data').append(row);
                }

                if (result.twitterSearch) {
                    var row3 = $('<div id="twtr-search-widget" class="tagdata corner"></div>');
                    $('#Data').append(row3);
                    row3.tweet({
                       query: result.topic,
                        join_text: "auto",
                       avatar_size: 32,
                        loading_text: "loading tweets..."
                    });
                }

                // expand all rendered json
                $("dt.collapsed").removeClass("collapsed").next().toggle();
                
                // Add 'external' CSS class to all external links
                $('a:external').addClass('external').attr('target', '_blank');

                $('.slideshow').remove();
                if (result.recording) {
                    $('#player,.jp-single-player').show();
                    // give some room
                    $('#maincontent').css('overflow-x', 'scroll');

                    var startTimeMili = new Date(result.recording.startDate).getTime();
                    console.log('start: ' + startTimeMili);
                    var mediaName;
                    $.each(result.recording['-media'], function(name, details) {
                        mediaName = name;
                    });

                    var url1 = '/' + db_name + '/' + wikid_id + '/-' + mediaName + '.mp3';
                    var url2 = '/' + db_name + '/' + wikid_id + '/-' + mediaName + '.ogg';
                    var disableScrubberUpdates = false;
                    var timeToDiv = [];
                    var iteration = 0
                    $.jPlayer.timeFormat.showHour = true;

                    $('#player').jPlayer({
                       swfPath: "scripts" ,
                        ready: function() {
                            if (!mainPlayerReady) {
                                this.element.jPlayer("setFile", url1, url2);
                                // look for an anchor in the url to play
                                if (location.hash) {
                                    var anchor = location.hash.substr(1);
                                    if(idToTag[anchor]) {
                                        var tag = idToTag[anchor];
                                        var startTime = tag.startTime;
                                        $('#player').jPlayer('play');
                                        $('#player').jPlayer('playHeadTime', startTime *1000);
                                    }
                                }
                            }
                            mainPlayerReady = true;
                        },
                        "warningAlerts" : true,
                        preload: "auto",
                        customCssIds: false
                    }).jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
                        $('#jplayer_play_time').text($.jPlayer.convertTime(playedTime));
                        $('#jplayer_total_time').text($.jPlayer.convertTime(totalTime));
                        if (!disableScrubberUpdates) {
                            $("#scrubber").slider('option', 'value', playedTime/1000 );
                            updatePlayhead();
                        }
                        iteration++;
                        if (iteration % 5 == 0) {
                            $.each(timeToDiv, function(i, val) {
                               var time = val.time;
                                if (time) {
                                    var curTime = playedTime/1000;
                                    if (time[0] <= curTime && time[1] >= curTime) {
                                        $(val.div).find(".streambar").addClass('ui-state-highlight');
                                    }
                                    else {
                                        var stbar = $(val.div).find(".streambar");
                                        if (!stbar.data('mouseover') ) {
                                            stbar.removeClass('ui-state-highlight');
                                        }
                                    }
                                }
                            });
                            // check for slides

                            //startTimeMili
                            var screenshotInfo = $('.slideshow').data('screenshotInfo');
                            if (screenshotInfo) {
                                var worldTime = playedTime + startTimeMili;
                                var indexSlideToShow = _.sortedIndex(screenshotInfo.attachments, worldTime) ;

                                if (indexSlideToShow >= 0) {
                                    var timeToShow = screenshotInfo.attachments[indexSlideToShow];
                                    var ss_url = wikid.screenshotUrl(db_name, screenshotInfo.id, timeToShow);
                                                            
                                    $('.slideshow').find('img').attr('src', ss_url);
                                }
                            }

                        }
                    });
                    if (mainPlayerReady) {
                        $('#player').jPlayer("setFile", url1, url2);
                        // look for an anchor in the url to play
                        if (location.hash) {
                            var anchor = location.hash.substr(1);
                            if(idToTag[anchor]) {
                                var tag = idToTag[anchor];
                                var startTime = tag.startTime;
                                $('#player').jPlayer('play');
                                $('#player').jPlayer('playHeadTime', startTime *1000);
                            }
                        }
                    }


                    var div = $('#markers');
                    
                    var constWidth = div.width();
                    var audioDuration = result.recording['-duration'];
                    var pps = wikid.ui.calculatePixelsPerSecond(div.width(), audioDuration, 1);
                    var spp = wikid.ui.calculateSecondsPerPixel(div.width(), audioDuration, 1);


                    var band = $('<div id="timeband"></div>');
                    div.append(band);
                    band.width(constWidth);
                    wikid.ui.createTimeBand(band,audioDuration, pps);

                    div.append('<div id="scrubber"></div>');
                    $("#scrubber").slider({
                            range: false,
                            min: 0,
                            max: audioDuration,
                            value: 0,
                            start: function(event, ui) {
                                disableScrubberUpdates = true;
                            },
                            stop:  function(event, ui) {
                                var time = $('#scrubber').slider('option', 'value');
                                $('#player').jPlayer('playHeadTime', time *1000);
                                disableScrubberUpdates = false;
                            }
                    }).width(constWidth);

                    var player = {
                        play: function(time) {
                            $('#player').jPlayer('playHeadTime', time *1000);
                        }
                    }

                    var segments = wikid.findSegments(wikid_id,db).rows;
                    segments = _.sortBy(segments, function(segment) { return segment.seconds});




                    var segmentsDiv = $('<div id="segments"></div>');
                    div.append(segmentsDiv);
                    $.each(segments, function(i, segment) {
                        var segmentDiv = $('<div class="segment"></div> ');
                        if (segment.value.seconds > 30000) return;

                        if (segment.value.duration < spp) return;

                        var marginLeft = wikid.ui.calculateSecondsPixelSize(segment.value.seconds, pps);
                        var width = wikid.ui.calculateSecondsPixelSize(segment.value.duration, pps);

                        var speaker = segment.value.gender + '-' + segment.value.speaker;
                        segmentDiv.attr('title', speaker);
                        segmentDiv.data('gender', segment.value.gender);
                        segmentDiv.data('speaker', segment.value.speaker);
                        segmentDiv.css('margin-left', marginLeft + 'px');
                        segmentDiv.width(width);
                        segmentsDiv.append(segmentDiv);

                        segmentDiv.css( 'cursor' , 'pointer');
                        segmentDiv.mouseover(function() {
                            $(this).addClass('ui-state-highlight').css('z-index', '1');
                            $(this).data('mouseover', true);
                        }).mouseout(function() {
                            $(this).removeClass('ui-state-highlight').css('z-index', null);;
                            $(this).data('mouseover', false);
                        })
                        .click(function(){
                           player.play(segment.value.seconds);
                        });

                    });
                    $('.segment').heatcolor(function(){
                        var title = $(this).attr('title');
                        var gender = $(this).data('gender');
                        var speaker = $(this).data('speaker');
                        var range = speaker.substring(1);
                        return range;

                    }, {
                            lightness: 0.3
                        });

                    var conversationTags = wikid.findConversationTags(wikid_id,db).rows;
                    conversationTags = _.sortBy(conversationTags, function(tag){return tag.value.timestamp});
                    var idToTag = {};
                    $.each(conversationTags, function(i,conversationTag) {
                        var div1 = wikid.ui.showTag(div, conversationTag.value, 1262325200000, pps, player);
                        idToTag[conversationTag.id] = conversationTag.value;
                        timeToDiv.push({time:[conversationTag.value.startTime,conversationTag.value.endTime], div: div1});
                    });
                    var playhead = $('#playhead');
                    playhead.draggable({
                        axis: "x",
                        containment: "#playheadHolder",
                        start: function() {
                            playhead.data('drag', true);
                        },
                        stop: function() {
                            var left = playhead.position().left;

                            var seconds = Math.round(left * spp);
                            $('#player').jPlayer('playHeadTime', seconds *1000);
                            playhead.data('drag', false);
                        }
                    }).mouseover(function() {
                        playhead.css('width', '3px');
                    }).mouseout(function() {
                        playhead.css('width', '2px');
                    });
                    updatePlayhead();
                    shortcut.add('Space', function() {
                        if ( $('#player').jPlayer("getData","diag.isPlaying")) {
                            $('#player').jPlayer('pause');
                        } else {
                            $('#player').jPlayer('play');
                        }
                    }, {disable_in_input: true});
                    shortcut.add('Right', function() {
                        var time = $('#player').jPlayer("getData","diag.playedTime");
                        var newTime = time + 30000;
                        $('#player').jPlayer('playHeadTime', newTime);
                    }, {disable_in_input: true});
                    shortcut.add('Left', function() {
                        var time = $('#player').jPlayer("getData","diag.playedTime");
                        var newTime = time - 30000;
                        $('#player').jPlayer('playHeadTime', newTime);
                    }, {disable_in_input: true});
                    shortcut.add('Shift+Right', function() {
                        var time = $('#player').jPlayer("getData","diag.playedTime");
                        var newTime = time + 600000;
                        $('#player').jPlayer('playHeadTime', newTime);
                    }, {disable_in_input: true});
                    shortcut.add('Shift+Left', function() {
                        var time = $('#player').jPlayer("getData","diag.playedTime");
                        var newTime = time - 600000;
                        $('#player').jPlayer('playHeadTime', newTime);
                    }, {disable_in_input: true});

                    $('#markers').lasso({
                        delay: 100,
                        stop: function(event, props) {

                        }
                    });

                    // check for slides

                    var results = db.view("screenshots/by_meeting", {key : doc._id});
                    if (results && results.rows && results.rows[0] && results.rows[0].value && results.rows[0].value.attachments) {
                        var slideShowDiv = $('<div class="slideshow"><img src=""/></div>');
                        $('#Info').after(slideShowDiv);
                        var screenshotInfo = results.rows[0].value;
                        screenshotInfo.attachments = results.rows[0].value.attachments.reverse();
                        var ss_url = wikid.screenshotUrl(db_name, screenshotInfo.id, screenshotInfo.attachments[0]);
                        $('.slideshow').data('screenshotInfo', screenshotInfo)
                                .find('img').attr('src', ss_url);
                    }



                }
                // There is a playlist to show
                if (result.playlist && result.playlist.length > 0) {

                    var internalPlaylist = [];
                    var internalIndex = 0;

                    function playListChange( index ) {
                        //console.log(index);
                        internalIndex = index;
                        var recording = internalPlaylist[internalIndex];
                        //console.dir(recording);
                        $('#player').data('recording', recording);
                        $('#player').jPlayer('setFile', recording.url);
                        $('#player').jPlayer('play');
                        if (recording.startOffset) {
                            $('#player').jPlayer('playHeadTime', recording.startOffset);
                        }
                       // var index = recording.index;
                        // highlight the one playing
                        //$('.playlistItem').removeClass('ui-state-highlight');
                        //$('.playlist .playlistItem:eq('+ index + ')').addClass('ui-state-highlight');


                    }

                    function playListNext() {
                        var index = (internalIndex+1 < internalPlaylist.length) ? internalIndex+1 : 0;
                        playListChange( index );
                    }


                    $.jPlayer.timeFormat.showHour = true;
                    $('#player').jPlayer({
                       swfPath: "scripts" ,
                        "warningAlerts" : true,
                        preload: "auto",
                        customCssIds: false
                    }).jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
                        var recording = $('#player').data('recording');
                        if (recording.endOffset && recording.endOffset > 0 && playedTime > recording.endOffset) {
                            playListNext();
                        }

                    }).jPlayer("onSoundComplete", function() {
                        playListNext();
                    });


                    $('.playlist').remove();
                    var playlistDiv = $('<div class="playlist"></div>');
                    $('#Data').after(playlistDiv);
                    $.each(result.playlist, function(i, item) {
                        var hide = '';
                        if (i > 0) hide = 'hidden';



                        var itemDiv = $('<div class="playlistItem '+hide+'"></div>').appendTo(playlistDiv);
                        itemDiv.data('item', item);
                        itemDiv.data('index', i);
                        var text = 'Tag';
                        if (item.text) text = item.text;
                        var date = new Date(item.start);
                        var end = new Date(item.end);
                        var duration = $.jPlayer.convertTime(item.end - item.start);
                        var dateText = date.toISOString();

                        var dateTextURL = date.toString("d-MMM-yyyy_h:mm:ss_tt");

                        var tagsToShow = _.without(item.tags,wikid_id);
                        var tagStr = " ";
                        if (tagsToShow && tagsToShow.length > 0) {
                            $.each(tagsToShow, function(i, tag) {
                                console.log(tag);
                                if (i > 0) {
                                    tagStr = tagStr + ", ";
                                }
                                tagStr = tagStr + wikid.getTagLinkHTML(wikid.getTagLink(tag));
                            });
                            tagStr = tagStr + '<span class="spacer"> </span>'
                        }
                        

                        var count = i + 1;
                        itemDiv.append('<span class="playlistItemControl paused"><img src="images/icons/control_play_2.png"/></span><span class="playlistItemText">'+ count + '. ' + text +  ' </span> '+tagStr+'<a href="timeline.html?'+ dateTextURL +'"><abbr class="timeago" title="'+dateText+'">'+dateText+'</abbr></a><span class="playlistItemDuration">'+ duration +  '</span>');

                        itemDiv.find('.playlistItemControl').click(function() {
                            if ($(this).hasClass('paused')) {

                                $('.playlistItem').removeClass('ui-state-highlight')
                                        .find('.playlistItemControl').addClass('paused')
                                        .parent().find('img').attr('src', 'images/icons/control_play_2.png');
                                $(this).removeClass('paused');
                                $(this).parent().addClass('ui-state-highlight');
                                $(this).find('img').attr('src', 'images/icons/control_pause_2.png');
                                internalPlaylist = findRecordingsForItem(i, item);
                                playListChange( 0 )
                            } else {
                                $(this).parent().removeClass('ui-state-highlight');
                                $(this).addClass('paused').find('img').attr('src', 'images/icons/control_play_2.png');
                                $('#player').jPlayer('pause');
                            }
                        })
                    });
                    $('.timeago').timeago();
                    
                    if (result.playlist.length > 1) {
                        var hiddenTotal = result.playlist.length - 1;
                        var showHide = $('<div class="playlistToggle">Show '+hiddenTotal+' more...</div>');
                        $('.playlist').append(showHide);
                        showHide.click(function(){
                            $(this).toggleClass('expanded');
                            if ($(this).hasClass('expanded')) {
                                $('.playlistItem:gt(0)').show('explode');
                                $(this).text('Show Less...');
                            } else {
                                $('.playlistItem:gt(0)').hide('explode');
                                $(this).text('Show '+hiddenTotal+' more...');
                            }
                        });
                    }


                    function findRecordingsForItem(index, item) {
                        // hack atack. We need to put the recordings in the db?
                        var start = item.start - 3600000; // before on hour
                        var end =  item.end + 3600000; // after on hour
                        var results = db.view("audio/by_time", {startkey:  start, endkey: end});

                        var recordings = [];
                        $.each(results.rows, function(i, test) {
                            if (test.value.type == 'recording') {
                                //console.log('item:\t' + item.start + '\t' + item.end);
                                //console.log('test:\t' + test.value.start + '\t' + test.value.end );
                                //console.log('---');
                                if ((item.start <= test.value.end && item.end >= test.value.end) || (item.start <= test.value.start && item.end >= test.value.start) || (item.start >= test.value.start && item.end <= test.value.end)) {
                                    var mediaName = _.keys(test.value.file)[0]
                                    var url =  '/' + db_name + '/' + test.id + '/' + mediaName ;
                                    var recording = {
                                         index: index,
                                         url: url
                                    }
                                    if (test.value.start <= item.start && item.start <= test.value.end) {
                                        var offset = item.start - test.value.start;
                                        recording.startOffset = offset;
                                    }
                                    if (test.value.start <= item.end && item.end <= test.value.end) {
                                        var offset = item.end - test.value.start ;
                                        recording.endOffset = offset;
                                    }
                                    recordings.push(recording);
                                }
                            }
                        });
                        //console.dir(recordings);
                        return recordings;

                    }


                }
                if (!result.recording && result.playlist.length == 0){
                    $('#player,.jp-single-player').hide();
                    $('#maincontent').css('overflow-x', 'hidden');
                }

                /** external links section**/
                $('.externalLinks').remove();
                var section =  $('<div class="externalLinks"><div class="externalLinkTeaser"><img src="images/icons/plus-grey.png"/> Add</div><h3>External Links</h3></div>');
                $('#maincontent').append(section);


                _.delay(function() {
                    var externalLinks = wikid.getExternalLinks(doc, settings);
                    if (externalLinks.length > 0) {
                       $.each(externalLinks, function(i, externalLink) {
                           showExternalLink(externalLink);
                        });
                    }
                    $('.externalLinks').mouseover(function() {
                        $('.externalLinkTeaser').show();
                    })
                    .mouseout(function() {
                        $('.externalLinkTeaser').hide();
                    });

                }, 10)
                //$('.innertube').loading();

                
                $('#topicIconDialog').dialog({
                    autoOpen: false,
                    resizable: true,
                    height: 240,
                    width: 600,
                    modal: true,
                    buttons : {
                        "Ok" : function() {
                            var icon = $('#topicIcon').val();
                            if (icon) {
                                doc['-icon'] = icon;
                                db.save(doc);
                                var icon_obj = {type:'type', icon: icon}
                                var icon_url = wikid.topicIconUrl(icon_obj, db_name, knownTypes);
                                $('.mainTopicImage').attr('src', icon_url);
                            }
                            $(this).dialog('close');
                        },
                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                });

                $('#freebaseDialog').dialog({
                    autoOpen: false,
                    resizable: true,
                    height: 240,
                    width: 600,
                    modal: true,
                    buttons : {
                        "Ok" : function() {
                            if (freebaseDataIdSelection) {
                               doc['-freebase_id'] = freebaseDataIdSelection;

                            } else {
                                doc['-freebase_id'] = null;
                            }
                            db.save(doc);
                            freebaseDataIdSelection = null;

                            $('.fbs-pane,.fbs-flyout-pane,.fbs-status').hide();
                            $(this).dialog('close');
                            showTopic();

                        },
                        Cancel: function() {
                            $('.fbs-pane,.fbs-flyout-pane,.fbs-status').hide();
                            $(this).dialog('close');
                        }
                    },
                     close: function(event, ui) {
                        $('.fbs-pane,.fbs-flyout-pane,.fbs-status').hide();
                     }
                });

                $('#twitterDialog').dialog({
                    autoOpen: false,
                    resizable: true,
                    height: 240,
                    width: 600,
                    modal: true,
                    buttons : {
                        "Ok" : function() {
                            var searchText = $('#twitterText').val();
                            if (!searchText) searchText = null;
                            doc['-twitter_search'] = searchText;
                            db.save(doc);
                            $(this).dialog('close');
                            showTopic();

                        },
                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                });

                $('#addAttachment').dialog({
                    autoOpen: false,
                    resizable: true,
                    height: 240,
                    width: 600,
                    modal: true,
                    buttons : {
                        "Ok" : function() {

                            var form = $("#upload-form");
                            var name = $('#attachmentFile').val();
                            $('#attachmentRevision').val(doc._rev);
                            form.ajaxSubmit({
                              url: db.uri + $.couch.encodeDocId(wikid_id),
                              success: function(resp) {
                                  _delay(showTopic, 200);
                                  

                              }
                            });

                            $(this).dialog('close');

                        },
                        Cancel: function() {

                            $(this).dialog('close');
                        }
                    },
                     close: function(event, ui) {
                       
                     }
                });


            } /** end of show topic **/

            function showExternalLink(externalLink) {
                var random = Math.floor(Math.random()*10000);
                var link = $("<span class='externalLink'><img src='http://www.bitpixels.com/getthumbnail?code="+random+"&url="+externalLink.url+"'/><br/><a class='external' href='"+ externalLink.url +"' target='_blank'>"+ externalLink.name + "</a></span>");
                link.appendTo('.externalLinks');
                
                link.find('img').click(function() {
                    var a = $(this).parent().find('a');
                    if (a && a[0]) {
                        var event = document.createEvent("HTMLEvents");
                        event.initEvent("click", true, true);
                        a[0].dispatchEvent(event);
                    }
                });
            }


            function setupInfoSection() {

                var dataWikiTagged = $('<div id="Data"></div><div id="Wiki"></div><div id="Tagged"><h3 id="tagged_title" class="padcontent"></h3><ul id="tagged_as"></ul></div>');
                $('#Info').empty().append(dataWikiTagged);
            }

            function setupMarkersSection() {
                var playheadHolder = $('<div id="playheadHolder"><div id="playhead" ></div></div>');
                $('#markers').empty().append(playheadHolder);
                $('.playlist').empty();
            }


            /****** end of topic.html import *****/
            // show spaces on left
            $.each(spaces, function(i, space){
                var spaceText = space;
                var class = '';
                if (space != db_name) {
                    spaceText = '<a href="/_'+space+'/">'+ space +'</a>';
                    class = 'leftListItem';
                } else {
                    class = 'selectedSpaceName';
                }

                var link = $('<div class="spaceName '+class+'">'+ spaceText +'</div>').appendTo('.spacesList');
                if (space == db_name) {
                    $('.selectedSpace').appendTo('.spacesList');
                }

            });



            $(window).bind( 'hashchange', function( event ) {
                var topic = parseTopic();
                var filters =  parsePath();

                if (topic && topic != wikid_id) {
                    wikid_id = topic;

                    _.defer(showTopic);


                }
                //$('.innertube').loading({align: 'top-middle', mask:true});
                highlightSelectedTopic();
                // check if the path given is different than that of the current displayed path
                var showingPath = getPathShowing();
                var samePath = isSamePath(showingPath, filters);
                if (!samePath) {
                    $('.breadCrumbFilter').empty();
                    $('.topicList').empty();
                    $.each(filters, function(i, filter) {

                        var crumb = addFilterToBreadCrumb(filter);
                        crumb.find('.crumbText').show();
                    });
                }

                // check something is showing if the filter path length is 0, but no items in the topiclist
                var rootRefresh = ($('.topicListItem').size() == 0 && filters.length == 0);


                if (rootRefresh || !samePath || loadPath || (!topic && filters.length == 0)) {
                    showCurrentFilter(filters);
                    loadPath = false;
               }
                  



            });

            function updatePlayhead() {
                var markers_offset = $('#markers').offset();
                var scrubber_offset = $('#scrubber a').offset();

                scrubber_offset.left = scrubber_offset.left - markers_offset.left + 29;
                scrubber_offset.top -= 22;
                var height = $('#markers').height();
                //var external_height = $('#external_tags_table').height();
                //height = height + external_height;
                height = height + "px";
                var left = scrubber_offset.left - 21;
                if (! $("#playhead").data('drag') ) {
                    $("#playhead").css({ 'left': left, 'height': height});
                }

            }

            function isSamePath(showingPath, filters) {
                //if (!showingPath && !filters) return true;
                if (showingPath.length == 0 && filters.length == 0) return true;
                if (showingPath.length != filters.length) return false;
                if (filters.length == 0) return false; // we do this so the next does not fail
                var same = true;
                $.each(filters, function(i, filter) {
                    var showingAtom =  showingPath[i];

                    if (showingAtom != filter ) {
                        same = false;
                    }
                });
                return same;


            }

            function getPathShowing() {
                var showingPath = [];
                $('.crumb').each(function() {
                    var topic = $(this).data('topic');
                    if (topic) showingPath.push(topic)
                });
                return showingPath;
            }


            function highlightSelectedTopic() {
                $('.topicListItem').removeClass('topicListItemSelected');
                if (wikid_id) {
                    $('.' + wikid.topicIdToClass(wikid_id)).addClass('topicListItemSelected');

                    if (placeArrow() && !dontScroll) {
                        $('.topicList').scrollTo('.topicListItemSelected');
                    }
                    dontScroll = false;
                }

                // highlight bookmark if needed
                var anchor = window.location.hash.substring(1);
                var bmarkLocation = -1;
                $.each(bookmarks, function(i, bookmark) {
                    if (bookmark === anchor)  bmarkLocation = i;
                });
                if (bmarkLocation > -1) {
                    $('.selectedSpaceFilter').removeClass('selectedSpaceFilter');
                    $('.bookmark').eq(bmarkLocation).addClass('selectedSpaceFilter');
                } else {
                    $('.selectedSpaceFilter').removeClass('selectedSpaceFilter');
                    $('.browseItem').addClass('selectedSpaceFilter');
                }

            }


            function placeArrow() {
                if ($('.topicListItemSelected:visible').size() > 0) {
                    $('.arrow').show().position({
                        of: $('.topicListItemSelected'),
                        my: 'left',
                        at: 'right',
                        offset: '0 0'
                    });
                    return true;
                } else {
                    $('.arrow').hide();
                    return false;
                }
            }

            $('.topicList').scroll(function() {
                placeArrow();
            })


            function showCurrentFilter(filters) {

                if (filters.length == 0) {
                    showRoot();
                }
                if (filters.length >0) {
                    showLevel(filters)
                }
                $('.topic').draggable({
                    opacity: 0.7,
                    helper: "clone",
                    distance: 30,
                    start: function(event, ui) {
                        $('#taglist').effect('bounce', {times:2}, 200);
                    }
                });
                $('.topicList').show('slide', 150, function() {
                    highlightSelectedTopic();
                });
            }


            function showLevel(path) {

                var results = db.view("system/tag_to_tags", {}, [path[0]]);
                var existingFilters = _.rest(path);
                if (existingFilters && existingFilters.length > 0);
                results.rows = _.filter(results.rows, function(row) {
                    var tags = row.value;
                    var found = [];
                    $.each(existingFilters, function(i, existingFilter) {
                        found[i] = _.contains(tags, existingFilter);
                    });
                    return _.all(found);
                })

                var filters = findFilters2(results, path);

                var filterKeys = _.keys(filters);

                $.each(filterKeys, function(i, filter) {
                    var filterSize = filters[filter];
                    if (filterSize == results.rows.length) return; // dont show it if it does nothing!
                    var item = $('<div class="topicListItem topicListFolder topicFilter"  ><img src="images/icons/folder-horizontal.png" alt="door" class="topicIcon"><div class="topicName">'+filter+'</div><span class="ui-icon ui-icon-triangle-1-e" title="Add Filter"></span><span class="topicCount">'+filters[filter]+'</span></div>')
                    //var item = $('<div class="topicListItem"  ><img src="images/icons/funnel--plus.png" alt="door" class="topicIcon"><div class="topicName">'+filter+'</div></div>');
                    item.appendTo('.topicList');
                    item.data('filter', filter   );
                });

                var topicsShown = []
                $.each(results.rows, function(i, row) {

                    var item = $('<div class="topic topicListItem '+wikid.topicIdToClass(row.id)+'"  title="'+row.id+'"><img src="images/icons/document.png" alt="door" class="topicIcon"><div class="topicName">'+row.id+'</div></div>');
                    item.appendTo('.topicList');
                    item.data('topic', row.id   );
                    topicsShown.push(row.id )
                });


                _.delay(showIcons, 20, topicsShown);

            }


            function showIcons(topicsShown) {
                var icons = db.view("system/by_icons", {}, topicsShown);
                $.each(icons.rows, function(i, row){
                    var iconLocation = wikid.topicIconUrl(row.value, db_name, knownTypes);
                   $('.' + wikid.topicIdToClass(row.id) + ' img').attr('src', iconLocation);
                })
            }



            function showOrphans(orphans) {
                $.each(orphans, function(i, topic) {
                    var item = $('<div class="topic topicListItem '+wikid.topicIdToClass(topic)+'"  title="'+topic+'" ><img src="images/icons/document.png" alt="door" class="topicIcon"><div class="topicName ">'+topic+'</div></div>');
                    item.appendTo('.topicList');
                    item.data('topic', topic   );
                });
                $('.topic').draggable({
                    opacity: 0.7,
                    helper: "clone",
                    distance: 30,
                    start: function(event, ui) {
                        $('#taglist').effect('bounce', {times:2}, 200);
                    }
                });
                _.delay(showIcons, 20, orphans);
            }

            function findFilters2(results, currentTopics) {
                var filters = {};
                $.each(results.rows, function(i, row) {
                    $.each(row.value, function(j, tag) {
                        var count = filters[tag];
                        if (!count) count = 0;
                        count++;
                        filters[tag] = count;
                    });
                });
                $.each(currentTopics, function(i, topic){
                    delete filters[topic];
                })
                return filters;
            }

            function showRoot() {
                var loose = db.view("navigation/loose_docs", {reduce: false});
                var loose_ids = _.pluck(loose.rows, 'id');

                var results = db.view("navigation/root_folders", {'group': true});
                var topicsShown = [];
                $.each(results.rows, function(i, row) {
                    var topic = row.key;
                    topicsShown.push(topic);
                    if (_.contains(loose_ids, topic)) {
                        loose_ids = _.without(loose_ids, topic);
                    }
                    var item = $('<div class="topic topicListItem topicListFolder '+wikid.topicIdToClass(row.key)+'"  title="'+row.key+'"><img src="images/icons/document-tag.png" alt="door" class="topicIcon"><div class="topicName">'+row.key+'</div><span class="ui-icon ui-icon-triangle-1-e" title="Show Children"></span><span class="topicCount">'+row.value+'</span></div>');
                    item.appendTo('.topicList');
                    item.data('topic', row.key);

                });
                
                if (loose_ids.length > 0) {
                    var item = $('<div class="topicListItem topicListFolder"  ><img src="images/icons/document-broken.png" alt="door" class="topicIcon"><div class="topicName orphan">Orphans</div><span class="ui-icon ui-icon-triangle-1-e" title="Show children"></span><span class="topicCount">'+loose_ids.length+'</span></div>');
                    item.prependTo('.topicList');
                    item.data('orphans', loose_ids);
                }

                _.delay(showIcons, 20, topicsShown);
            }


            function parseTopic() {
                var hash = $.param.fragment();
                if (hash.indexOf('|') >= 0) {
                    return hash.split('|')[1];
                }
                else return hash;

            }


            function parsePath() {
                var hash = $.param.fragment();
                var filters = [];
                if (hash.indexOf('|') < 0) return filters;
                var path = hash.split('|')[0].split('/');

                $.each(path, function(i, atom) {
                    filters.push(atom);

                });
                return filters;
            }

            function changeURL(topic, path) {
                if (!path) {
                    path = [];
                    $('.crumb').each(function() {
                        var topic = $(this).data('topic');
                        path.push(topic);
                    });
                }
                var anchor = wikid.generateAnchor(path, topic)
                var hash = '#' + anchor;
                $.bbq.pushState(hash);

                //window.location.hash = hash;
            }
            
            function resizeTopicList() {
                $('.column,.topicList,.innertube').height($(window).height() - 25);
                var height = $('#rightcolumn').height() - $('.breadCrumbFilter').height() - 34 - $('.topicListActions').height(); // 30 is the margin top
                $('.topicList').height(height);

            }

            $('.bookmarkAction').live('click', function() {
                
            });

            /***************** Search Auto Complete ***************************/

            $('#wikiLinks').dialog({
                autoOpen: false,
                resizable: true,
                height: 150,
                width: 215,
                modal: true,
                buttons : {
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
            $('#internalLink').autocomplete({
                minLength: 1,
                delay: 400,
                'z-index': 5,
                source: function(request, response) {
                    var term = request.term;
                    term = term.toLowerCase();
                    var allResults = [];
                    $.each(spaces, function(i, space) {
                        var space_db = new CouchDB(space);
                        var matches = space_db.view("system/topics", {
                            startkey: term,
                            endkey: term + 'zzz',
                            limit: 10
                        });
                        if (matches.rows && matches.rows.length > 0) {
                            matches.rows = _.map(matches.rows, function(row){ row.value.db = space; return row;})
                            allResults = allResults.concat(matches.rows);
                        }
                    });

                    var result = _.map(allResults, function(row) { return  row.value});
                    result = _.sortBy(result, function(row) { return row._id });
                    response(result);


                },
                focus: function(event, ui) {
                    $(this).val(ui.item._id).data('item', ui.item);
                },
                select: function(event, ui) {

                }
            }).bind('autocompleteclose keyup', function(e) {
                if (e && (e.keyCode != 13 && e.keyCode != 0))  return;
                var newWikid_id = $(this).val();
                var item = $(this).data('item');
                var db = item.db;
                var path = "#";
                if (db_name != db) {
                    // we need to change the url to the new db
                    path = "/_" + db + "/#";
                    if (item.type && item.type != 'topic') {
                        path = path + item.type + "|";
                    }
                }
                var wym = $('#wikiLinks').data('editor');
                if (wym) {
                    var url = path + newWikid_id;
                    wym.wrap('<a href="'+url+'">','</a>');
                }
                $(this).val('');
                $('#wikiLinks').dialog('close');
                return false;

            }).data('autocomplete')._renderItem = function(ul, item) {

                if (item.type) {
                    item.icon.parent = item.type;
                }
                var icon = wikid.topicIconUrl(item.icon, item.db, knownTypes);


                return $('<li></li>')
                       .data('item.autocomplete', item)
                       .append('<a><img src="'+icon+'" class="searchImage"/><span class="searchResult">' + item._id + '</span><div class="searchDB">' + item.db + '</div></a>')
                       .appendTo(ul);
            };

            $('#mainSearch').autocomplete({
                minLength: 1,
                delay: 400,
                'z-index': 5,
                source: function(request, response) {
                    var term = request.term;
                    term = term.toLowerCase();
                    var allResults = [];
                    $.each(spaces, function(i, space) {
                        var space_db = new CouchDB(space);
                        var matches = space_db.view("system/topics", {
                            startkey: term,
                            endkey: term + 'zzz',
                            limit: 10
                        });
                        if (matches.rows && matches.rows.length > 0) {
                            matches.rows = _.map(matches.rows, function(row){ row.value.db = space; return row;})
                            allResults = allResults.concat(matches.rows);
                        }
                    });

                    var result = _.map(allResults, function(row) { return  row.value});
                    result = _.sortBy(result, function(row) { return row._id });
                    response(result);


                },
                focus: function(event, ui) {
                    $(this).val(ui.item._id).data('item', ui.item);


                },
                select: function(event, ui) {

                }
            }).bind('autocompleteclose keyup', function(e) {
                if (e && (e.keyCode != 13 && e.keyCode != 0))  return;
                var newWikid_id = $(this).val();
                var item = $(this).data('item');
                var db = item.db;
                if (db_name != db) {
                    // we need to change the url to the new db
                    var path = "";
                    if (item.type && item.type != 'topic') {
                        path = item.type + "|";
                    }


                    window.location = "/_" + db + "/#" + path + newWikid_id;
                    return false;
                }



                if (newWikid_id && newWikid_id !== '' && newWikid_id != wikid_id) {
                    var path = null;
                    if (item.type && item.type != 'topic') {
                        path = [item.type];
                    }
                    changeURL($(this).val(), path);
                }
                $(this).val('');

            }).data('autocomplete')._renderItem = function(ul, item) {

                if (item.type) {
                    item.icon.parent = item.type;
                }
                var icon = wikid.topicIconUrl(item.icon, item.db, knownTypes);


                return $('<li></li>')
                       .data('item.autocomplete', item)
                       .append('<a><img src="'+icon+'" class="searchImage"/><span class="searchResult">' + item._id + '</span><div class="searchDB">' + item.db + '</div></a>')
                       .appendTo(ul);
            };



            //showCurrentFilter();
            $(window).trigger( 'hashchange' );

            _.delay(resizeTopicList);

            $('.toolsMenu').live('mouseover', function() {
                $(this).find('div').addClass('toolsMenuHover').end().find('ul').show();
            }).live('mouseout',function() {
                $(this).find('div').removeClass('toolsMenuHover').end().find('ul').hide();
            }).find('li').live('click', function() {
                $(this).parent().hide();
            });

            $('.topicIconAction').click(function() {
                $('#topicIconDialog').dialog('open');
            });
            $('.freebaseAction').click(function() {
                $('#freebaseText').val('');     
                $('#freebaseDialog').dialog('open');
            });
            
            $('#freebaseText').suggest().bind("fb-select", function(e, data) {
              freebaseDataIdSelection = data.id;

            });

            $('.attachmentAction').click(function() {
                $('#addAttachment').dialog('open');
            });

            $('.twitterAction').click(function() {
                $('#twitterText').val('');
                $('#twitterDialog').dialog('open');
            });
            $('.deleteAction').click(function() {
				// need a conf dialog
				db.deleteDoc(doc);
				// where do we go?
				window.location = "./";
				return false;
			});

        })
     </script>
    <style type="text/css">
        .ui-slider-horizontal .ui-slider-handle {
        background: white url(styles/images/ui-icons_222222_256x240.png) no-repeat scroll 50% 50%;
            background-position: -64px 0;
            border-style: 1px solid #CECECE;
            cursor: move;
            z-index: 21;
        }
        .ui-slider-horizontal {
            border-style: none;
        }
    </style>
</head>
<body>
<div id="maincontainer">

<div id="contentwrapper">
    <div id="contentcolumn" class="column">
        <div class="innertube">
                <div id="maincontent">


                    <div id="titleHolder" id="title" class="hidden">
                        <img src="images/icons/user-gray.png" alt="" class="mainTopicImage" />
                        <span id="title"  class="readableId padcontent" title=""></span>
                        <div class="toolsMenu" title="">
                            <div>Topic<img src="images/icons/dropdown.png"/></div>
                            <ul>
                                <li class="topicIconAction">Set Icon</li>
                                <li class="attachmentAction">Add Attachment</li>
                                <li class="freebaseAction">Link To Freebase</li>
                                <li class="twitterAction">Link To Twitter</li>
                                <li class="renameAction">Rename</li>
                                <li class="deleteAction">Delete</li>
                            </ul>
                        </div>
                    </div>
                    <div id="lastmodified" class="padcontent hidden"></div>
                    <div id="taglist" class="corner hidden">

                    </div>

                    <div id="Info" class="padcontent content-container"></div>

                    <div id="player" class="jp-single-player"></div>
                    <div id="playerControls" class="jp-single-player hidden">
                        <div class="jp-interface">
                            <ul class="jp-controls">
                              <li><a href="#" id="jplayer_play" class="jp-play" tabindex="1">play</a></li>
                              <li><a href="#" id="jplayer_pause" class="jp-pause" tabindex="1">pause</a></li>

                            </ul>


                            <div id="jplayer_play_time" class="jp-play-time"></div>
                            <div id="jplayer_total_time" class="jp-total-time"></div>
                        </div>
                    </div>

                    <div id="markers"></div>
                </div>
        </div>

    </div>
</div>

<div id="leftcolumn" class="column">
    <div class="mainLogo">
        <img  src="images/corner_logo.png" alt="Eckoit Logo" />
    </div>
    <div class="leftListItem mainLink dashboardLink"><a href="dashboard.html"><img src="images/icons/compass.png" class="topicIcon"/>Dashboard</a></div>
    <div class="leftListItem mainLink "><a href="startMeeting.html"> <img src="images/icons/microphone.png"class="topicIcon">Record Meeting</a></div>
    <p class="leftHeader">SPACES</p>
    <div class="spaces">
        <div class="spacesList">
            <div class="selectedSpace">
                <div class="selectedSpaceFilter browseItem"><a href="./"><img src="images/icons/ui-scroll-pane-list.png" class="topicIcon"/>Topics</a></div>
                <div class="leftListItem timelineItem"><a href="timeline.html"><img src="images/icons/timeline_marker.png" class="topicIcon"/>Timeline</a></div>

                <!--
                <div class="leftListItem bookmark"><a href="/_personal/overview.html"><img src="images/icons/user-silhouette.png" class="topicIcon"/>Person</a></div>
                <div class="leftListItem bookmark"><a href="/_personal/overview.html"><img src="images/icons/layer-shape-ellipse.png" class="topicIcon"/>Project</a></div>
                -->
            </div>
        </div>
    </div>

    <p class="leftHeader">SEARCH</p>
    <input id="mainSearch" type="text"/>
</div>

<div id="rightcolumn" class="column">

    <div class="topicListActions">
        <div class="topicListAction newTopicAction" title="Add new topic"><img src="images/icons/grey-document--plus.png" class="topicIcon"/>New</div>
        <div class="topicListAction bookmarkAction" title="Bookmark current path..."><img src="images/icons/grey-book-open-bookmark.png" class="topicIcon"/>Bookmark</div>

    </div>
    <div class="breadCrumbFilter"></div>

    <div class="topicList">
  
    </div>

</div>
<div id="footer">
    <a href="http://eckoit.com/">Eckoit Inc</a>
</div>

</div>
<div class="arrow"></div>

 <div id="bookmarkDialog" title="Create Bookmark">
     <span  class="dialogName"><b>Name</b></span>
     <input type="text" id="bookmarkName"  class="dialogInput"/>
     <br/>
     <span  class="dialogName"><b>Icon</b></span>
     <input type="text" id="bookmarkIcon"  class="dialogInput  iconInput"/>
     <img src="" alt="" class="bookmarkIconImage" />
 </div>
 <div id="topicIconDialog" title="Topic Icon">
     <span  class="dialogName"><b>Icon</b></span>
     <input type="text" id="topicIcon"  class="dialogInput iconInput"/>
     <img src="" alt="" class="bookmarkIconImage" />
 </div>
 <div id="freebaseDialog" title="Freebase Topic">
     <span  class="dialogName"><b>Freebase Topic</b></span>
     <input type="text" id="freebaseText"  class="dialogInput"/>
 </div>
 <div id="twitterDialog" title="Twitter Topic">
     <span  class="dialogName"><b>Twitter Search</b></span>
     <input type="text" id="twitterText"  class="dialogInput"/>
 </div>
 <div id="addAttachment" title="Add Attachment...">
     <form method="post" id="upload-form">
         <input type="hidden" name="_rev" id="attachmentRevision"/>
         <input type="file" id="attachmentFile" name="_attachments"  class="dialogInput"/>
     </form>

 </div>
 <div id="wikiLinks" title="Link To Topic...">
     <input type="text" id="internalLink"  class="dialogInput"/>
 </div>
 <div id="newTopic" title="New Topic...">
     <form>
        <input type="text" id="newTopicName" class="dialogInput"/>
     </form>
 </div>
</body>
</html>
